package cn.tedu.jdbc;

import cn.tedu.jdbc.utils.DbUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 *使用批处理操作，向t_batch表中插入一万条记录，并记录耗时
 */
public class JDBCTest20 {
    public static void main(String[] args) {
        long begin = System.currentTimeMillis();
        Connection conn = null;
        PreparedStatement ps = null;

        try {
            conn = DbUtils.getConnection();
            String sql = "insert into t_batch(id,name) values(?,?)";
            ps = conn.prepareStatement(sql);
            int count = 0;
            for (int i = 1; i<=10000;i++){
                ps.setLong(1,i);
                ps.setString(2,"张三"+i);
                //打包
                ps.addBatch();
                if (i % 1000 ==0){
                   count += ps.executeBatch().length;
                }
            }
            //结束后再次执行批处理，防止非整数的数据
            count += ps.executeBatch().length;
            System.out.println("成功插入"+count+"条记录");
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            DbUtils.close(conn,ps,null);
        }
        long end = System.currentTimeMillis();
        System.out.println("耗时："+(end-begin)+"毫秒");
    }
    /**
     * 成功插入10000条记录
     * 耗时：355毫秒
     */
}
